package com.cnebula.uas.authtoken.service.impl;

import javax.annotation.PostConstruct;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import com.cnebula.uas.authtoken.ConfAdmin;
import com.cnebula.uas.authtoken.service.UASService;

@Service
public class UASServiceImpl implements UASService {

	public static final String CHECK_ARTIFACT = "/amconsole/SimpleRestService";
	
	Logger log = LoggerFactory.getLogger(UASServiceImpl.class);

	CloseableHttpClient httpClient = HttpClients.createDefault();

	@Autowired
	ConfAdmin conf;

	String checkArtifactURL;

	@PostConstruct
	public void init() {
		String uasURL = "http://" + conf.uasHost + ":" + conf.uasPort;

		checkArtifactURL = uasURL + CHECK_ARTIFACT;
	}

	@Override
	public ResponseEntity<String> checkArtifact(String artifact) throws Exception {


		CloseableHttpResponse res = null;
		String content = null;
		try {
			URIBuilder builder = new URIBuilder(checkArtifactURL);
			builder.setParameter("loginType", "cd");
			builder.setParameter("artifact", artifact);
			HttpGet httpGet = new HttpGet(builder.build());
			
			res = httpClient.execute(httpGet);
			HttpEntity entity = res.getEntity();
			content = EntityUtils.toString(entity);
			EntityUtils.consume(entity);

		} finally {
			if (res != null) {
				res.close();
			}

		}

		return ResponseEntity.ok(content);
	}


}
